<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../sources/layui/css/layui.css">
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
 
 <!-- 添加的from表单 -->
 <form class="layui-form" action="" id="addForm" style="display:none" lay-filter="add" enctype="multipart/form-data">
    <div class="layui-form-item">
      <label class="layui-form-label">车主</label>
      <div class="layui-input-block">
        <input type="text" id="carOwner" name="carOwner" lay-verify="carOwner" autocomplete="off" placeholder="车主" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">型号</label>
      <div class="layui-input-block">
        <input type="text" id="model" name="model" lay-verify="model" autocomplete="off" placeholder="型号" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">里程数</label>
      <div class="layui-input-block">
        <input type="text" id="mileage" name="mileage" lay-verify="mileage" autocomplete="off" placeholder="里程数" class="layui-input">
      </div>
    </div>
     <div class="layui-form-item">
      <label class="layui-form-label">发动机排量</label>
      <div class="layui-input-block">
        <input type="text" id="engineCapacity" name="engineCapacity" lay-verify="engineCapacity" autocomplete="off" placeholder="发动机排量" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">生产年份</label>
      <div class="layui-input-inline">
        <input type="date" id="productiveDate" name="productiveDate" lay-verify="productiveDate" autocomplete="off" placeholder="生产年份" class="layui-input">
      </div>
      
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">购买日期</label>
      <div class="layui-input-inline">
        <input type="date" id="purchaseDate" name="purchaseDate" lay-verify="purchaseDate" autocomplete="off" placeholder="生产年份" class="layui-input">
      </div>
      
    </div>
    
	<div class="layui-form-item" id="sub">
    	<button style="" class="layui-btn" type="button" lay-submit lay-filter="demo2" id="addsub">提交</button>
  	</div>
 </form>
 
 <!--修改的from表单 -->
 <form class="layui-form" action="" id="updataForm" style="display:none" lay-filter="updata" enctype="multipart/form-data">
    <div class="layui-form-item" style="display:none">
      <label class="layui-form-label">id</label>
      <div class="layui-input-block">
        <input type="text" id="id" name="id" lay-verify="id" autocomplete="off" placeholder="id" class="layui-input">
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">车主</label>
      <div class="layui-input-block">
        <input type="text" id="carOwner" name="carOwner" lay-verify="carOwner" autocomplete="off" placeholder="车主" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">型号</label>
      <div class="layui-input-block">
        <input type="text" id="model" name="model" lay-verify="model" autocomplete="off" placeholder="型号" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">里程数</label>
      <div class="layui-input-block">
        <input type="text" id="mileage" name="mileage" lay-verify="mileage" autocomplete="off" placeholder="里程数" class="layui-input">
      </div>
    </div>
     <div class="layui-form-item">
      <label class="layui-form-label">发动机排量</label>
      <div class="layui-input-block">
        <input type="text" id="engineCapacity" name="engineCapacity" lay-verify="engineCapacity" autocomplete="off" placeholder="发动机排量" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">生产年份</label>
      <div class="layui-input-inline">
        <input type="date" id="productiveDate" name="productiveDate" lay-verify="productiveDate" autocomplete="off" placeholder="生产年份" class="layui-input">
      </div>
      
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">购买日期</label>
      <div class="layui-input-inline">
        <input type="date" id="purchaseDate" name="purchaseDate" lay-verify="purchaseDate" autocomplete="off" placeholder="生产年份" class="layui-input">
      </div>
      
    </div>
	<div class="layui-form-item" id="sub">
    	<button style="" class="layui-btn" type="button" lay-submit lay-filter="demo3" id="updatasub">提交</button>
  	</div>
 </form>
 
<table class="layui-hide" id="test" lay-filter="test"></table>
 
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
	<button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加车辆信息</button>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
    <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
  </div>
</script>
 
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
              
          
<script src="../sources/layui/layui.js"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 --> 
 
<script>
layui.use('table', function(){
  var table = layui.table;
  
  table.render({
    elem: '#test'
    ,url:'http://localhost:8080//maven02/manage/selectAll'
    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
      title: '提示'
      ,layEvent: 'LAYTABLE_TIPS'
      ,icon: 'layui-icon-tips'
    }]
    ,title: '用户数据表'
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field:'id', title:'编号', width:100, fixed: 'left', unresize: true, sort: true}
      ,{field:'carOwner', title:'车主', width:120, edit: 'text'}
      ,{field:'model', title:'型号', width:120, edit: 'text'}
      ,{field:'mileage', title:'里程数', width:120, edit: 'text'}
      ,{field:'engineCapacity', title:'发动机排量', width:120, edit: 'text'}
      ,{field:'productiveDate', title:'生产年份', width:120, edit: 'text'}
      ,{field:'purchaseDate', title:'购买日期', width:120, edit: 'text'}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
    ]]
    ,page: true
    ,limit: 10
    ,response:{
		statusName: 'status' //规定数据状态的字段名称，默认：code
		,dataName: 'rows' //规定数据列表的字段名称，默认：data
	} 
	,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
		return {
	        "status": res[0].status,   //解析接口状态
	        "message":res[1].message,  //解析提示文本
	        "count": pagecount,       //解析数据长度
	        "rows": res[3].rows.item  //解析数据列表
	    };
  	}
	});
  
 //头工具栏事件
 table.on('toolbar(test)', function(obj){
   var checkStatus = table.checkStatus(obj.config.id);
   switch(obj.event){
     case 'getCheckData':
       var data = checkStatus.data;
       layer.alert(JSON.stringify(data));
     break;
     case 'getCheckLength':
       var data = checkStatus.data;
       layer.msg('选中了：'+ data.length + ' 个');
     break;
     case 'isAll':
       layer.msg(checkStatus.isAll ? '全选': '未全选');
     break;
     
     //自定义头工具栏右侧图标 - 提示
     case 'LAYTABLE_TIPS':
       layer.alert('这是工具栏右侧自定义的一个图标按钮');
     break;
     case 'add':
         add();
     break;
   };
 });
 
//add方法
 function add(){	 
	 layer_index= layer.open({
		  type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
		  title: "添加", //数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
		  area: ['500px', '400px'], //所打开页面大小
		  content:$("#addForm"), //内容
		  //关闭操作
		  cancel: function(){
			layer.close(layer_index);
			$("#addForm")[0].reset();
			$('#demoe1').attr('src', "");	  
		  }
	 }); 
	//刷新页面
	table.reload('test', {
		url: 'http://localhost:8080//maven02/manage/selectAll'
	});
 }

 
//引入from表单
 layui.use(['form', 'laydate'], function(){
	var laydate = layui.laydate;
	form = layui.form;
	form.render();
		
	//表单添加
	  form.on('submit(demo2)', function(data){
	    console.log(JSON.stringify(data.field));
	    $.ajax({   
	          url:'http://localhost:8080//maven02/manage/insert',       
	          method:'get',
	         
	          data:data.field,        
	          dataType:'JSON',  
	          success:function(res){       
	               if(res.status=='1'){ 
	    			console.log(res.status);	
	              	 	layer.msg("添加成功");
	              		$("#addForm")[0].reset();
	                	form.render();
	                	table.reload('test', {
		        			url: 'http://localhost:8080//maven02/manage/selectAll'
		 			            	});
	            	 	page();
	               }else{
	               	layer.msg("添加失败");  
	                $("#addForm")[0].reset();
	                form.render();
	               }            
	          },
	           error:function (data) {
	              	layer.msg("网络错误");
	               $("#addForm")[0].reset();
	               form.render(); 
	          } 
	         }) ;
	      layer.close(layer_index);
	  });
	//表单修改
	  form.on('submit(demo3)', function(data){
		 console.log(JSON.stringify(data.field));
		 $.ajax({   
		      url:'http://localhost:8080//maven02/manage/updateByPrimaryKey',       
		      method:'get',
		      data:data.field,        
		      dataType:'JSON',  
		      success:function(res){       
		           if(res.status=='1'){ 
		 			console.log(res);	
		 			
	 				layer.msg("修改成功");
	          		$("#updataForm")[0].reset();
	            	form.render();
	        		table.reload('test', {
	        			url: 'http://localhost:8080//maven02/manage/selectAll'
	 			            	});
	        	 	page();
		 			
		           }else{
		           	layer.msg("修改失败");  
		            $("#updataForm")[0].reset();
		            form.render();
		           }            
		      },
		         error:function (data) {
		          	layer.msg("网络错误");
		           $("#updataForm")[0].reset();
		           form.render(); 
		      } 
		     }) ;
		  layer.close(layer_index);
	 });
 
});

	
	
	 
  //监听行工具事件
  table.on('tool(test)', function(obj){
    var data = obj.data;
    //console.log(obj)
    if(obj.event === 'del'){
      layer.confirm('真的要删除么', function(index){
        obj.del();
        
        //删除
   		deleteCarInfo(data.id);
        
        layer.close(index);
      });
    } else if(obj.event === 'edit'){
    	form.val("updata", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
  		  "id": data.id // "name": "value"
  		  ,"carOwner":data.carOwner
  		  ,"model":data.model
  		  ,"mileage": data.mileage
  		  ,"engineCapacity": data.engineCapacity
  		  ,"productiveDate": data.productiveDate
		  ,"purchaseDate": data.purchaseDate
  		});
  	//修改方法
    	updateById(data);
    } 
  });
//删除
  function deleteCarInfo(index) {
	  $.ajax({
	  	    type: "get", //指定提交的类型 get对应 doGet()方法，post--->doPost()犯法
	  	    url: "http://localhost:8080//maven02/manage/deleteByPrimaryKey",    //传输地址的URL
	  	    data: {"id":index}, //data代表我们的数据  key -value类型的数据
	  	    dataType:'JSON',  
	  	    async : false, //success和error代表是否返回成功，既后台给前台传输数据是否成功
	  	    success: function (res)
	  	    {
	  			console.log(res);
	  			layer.msg("删除成功"); 
	  			table.reload('test', {
	  				url: 'http://localhost:8080//maven02/manage/selectAll'
	  			});
	  	    },
	  	    error:function (XMLHttpRequest, textStatus, errorThrown) { 
	  	        alert(typeof(errorThrown));
	  	     }
	  	});
}

//修改
  function updateById(data){
	 
	  layer_index= layer.open({
		  type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
		  title: "修改", //数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
		  area: ['500px', '400px'], //所打开页面大小
		  content:$("#updataForm"), //内容
		  //将数据显示在框上边
		
		  //关闭操作
		  cancel: function(){
			layer.close(layer_index);
			$("#updataForm")[0].reset();
			
		  }
	 }); 
	//刷新页面
	table.reload('test', {
		url: 'http://localhost:8080//maven02/manage/selectAll'
	});
	//刷新已入住页面
	//top.window['h_userSelectedInfo'].frames.location.reload();
  }

});



//计算页数
var pagecount;
page();
function page(){
	  $.ajax({
		url: 'http://localhost:8080//maven02/manage/countAll',
	        dataType: 'json',
	        type: 'get',
	        async:false,
	        success: function(data) {
	            pagecount = data.count;
	            //console.log(data.count)
	            console.log(pagecount)
	            }
	          });
}
console.log(pagecount);
</script>

</body>
</html>